package jpack.sz;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 7-zip wrapper
 * 
 * @author Denis Migol
 * 
 */
public class Sz {
	// TODO

	public static final String DEFAULT_PATH = "c:\\Program Files\\7-Zip\\";

	public static final String _7Z = "7z";

	private final String path;

	/**
	 * 
	 */
	public Sz() {
		this(DEFAULT_PATH);
	}

	/**
	 * 
	 * @param path
	 */
	public Sz(final String path) {
		super();
		this.path = path;
	}

	/**
	 * @return the path
	 */
	public String getPath() {
		return path;
	}

	/**
	 * 
	 * @param command
	 * @return
	 */
	private String correctCommand(final String command) {
		final String cmd = command == null ? "" : command.toLowerCase();
		final StringBuilder rarCmd = new StringBuilder(path);
		rarCmd.append(cmd.startsWith(_7Z) ? cmd : _7Z + ' ' + cmd);
		return rarCmd.toString();
	}

	/**
	 * 
	 * @param in
	 * @return
	 * @throws IOException
	 */
	private static String readInputStream(final InputStream in) throws IOException {
		final BufferedReader br = new BufferedReader(new InputStreamReader(in, "cp866"));
		final StringBuilder message = new StringBuilder();
		String line = null;
		while ((line = br.readLine()) != null) {
			if (!"".equals(line)) {
				message.append(line + "\n");
			}
		}
		message.deleteCharAt(message.length() - 1);
		return message.toString();
	}

	/**
	 * 
	 * @param command
	 * @return
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public SzResponse execute(final String command) throws IOException, InterruptedException {
		final Process process = Runtime.getRuntime().exec(correctCommand(command));
		final String message = readInputStream(process.getInputStream());
		final int code = process.waitFor();
		return new SzResponse(code, message);
	}

	/**
	 * Test
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(final String[] args) throws Exception {
		final SzResponse response = new Sz().execute(null);

		System.out.println(response.getCode());
		System.out.println(response.getMessage());
	}

}
